<template>
    <eui-background type="common">
        <eui-nav-bar title="售后单详情" color="#fff" rightIcon="">
            <template v-slot:right="">
                <view @click="confirmAudit">稽核</view>
            </template>
        </eui-nav-bar>
        <view class="footer" :style="{ 'overflow-y': 'scroll' }">
            <scroll-view scroll-y="true" style="height: 100%;">
                <m-card :title="false">
                    <template v-slot:content="">
                        <view class="flex align-center"
                            style="min-height: 60px;padding: 4px;margin-bottom: 8px;font-size: 32rpx;font-weight: bold;">
                            <view style="width: 30%;text-align: center;">{{ getBcmDictName('afsOrderStatus',
                                bcmAfsOrder.afsOrderStatus) }}</view>
                            <view style="width: 70%;">
                                <view class="flex align-center">
                                    <view
                                        :style="{ background: getBcmDictItem('chnlType', bcmAfsOrder.chnlType).color, marginRight: '8px' }"
                                        class="chnltype">{{ getBcmDictItem('chnlType', bcmAfsOrder.chnlType).text }}
                                    </view>
                                    <view v-if="!!bcmAfsOrder.thirdOrderIndex"
                                        style="font-size: 42rpx;font-weight: bold;color: #ff0000;">
                                        #{{ bcmAfsOrder.thirdOrderIndex }}
                                    </view>
                                    <view
                                        style="width:70rpx;height: 70rpx;border-radius: 70rpx;background:#EDEDED;margin-left: auto;margin-right: 36rpx;"
                                        class="flex align-center just-center" @click.stop="setPrint">
                                        <image :src="_img_printer" style="height: 33rpx;width: 42rpx;"></image>
                                    </view>
                                </view>
                                <view class="flex" style="margin: 14rpx 0;">
                                    <view class="tag" style="margin-right: 8px;">{{ getBcmDictItem('dealType',
                                        bcmAfsOrder.dealType).text }}</view>
                                    <view class="tag">{{ getBcmDictItem('returnGoodsType',
                                        bcmAfsOrder.returnGoodsType).text }}</view>
                                </view>
                                <view class="flex">
                                    <view style="margin-left: 6rpx;font-size: 28rpx;">
                                        发起时间<text style="color:#E43E00;margin-left: 9rpx;">{{
                                            bcmAfsOrder.sponsorTime }}</text>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </template>
                </m-card>
                <m-card :title="true" templateTitle="取件信息">
                    <template v-slot:content="">
                        <view class="font-13" style="padding: 8px 4px;font-size: 32rpx;">
                            <view class="flex ht-30">
                                <view class="co-9e" style="margin-right: 15px;">退货取件方式</view>
                                <view>{{ getBcmDictItem('returnGoodsPickType', bcmAfsOrder.returnGoodsPickType).text
                                    }}
                                </view>
                            </view>
                            <view class="flex ht-30">
                                <view class="co-9e" style="margin-right: 15px;">顾客姓名</view>
                                <view>{{ bcmAfsOrder.contactName }}</view>
                            </view>
                            <view class="flex ht-30">
                                <view class="co-9e" style="margin-right: 15px;">顾客电话</view>
                                <view>{{ bcmAfsOrder.contactPhone }}</view>
                            </view>
                            <view class="flex ht-30" v-if="bcmAfsOrder.shipperName">
                                <view class="co-9e" style="margin-right: 15px;">配送员姓名</view>
                                <view>{{ bcmAfsOrder.shipperName }}</view>
                            </view>
                            <view class="flex ht-30" v-if="bcmAfsOrder.shipperPhone">
                                <view class="co-9e" style="margin-right: 15px;">配送员电话</view>
                                <view>{{ bcmAfsOrder.shipperPhone }}</view>
                            </view>
                            <view class="flex">
                                <view class="co-9e" style="margin-right: 15px;">取件地址</view>
                                <view class="flex-1">{{ bcmAfsOrder.pickUpAddress }}</view>
                            </view>
                        </view>
                    </template>
                </m-card>
                <m-card :title="true" templateTitle="基本信息" :type="true" v-show="true">
                    <template v-slot:content="">
                        <view style="padding: 8px 4px;font-size: 32rpx;">
                            <view class="flex ht-30">
                                <view class="co-9e" style="margin-right: 15px;">售后单号</view>
                                <view>{{ bcmAfsOrder.afsOrderNo }}</view>
                            </view>
                            <view class="flex ht-30">
                                <view class="co-9e" style="margin-right: 15px;">原订单号</view>
                                <view>{{ bcmAfsOrder.thirdOrderNo }}</view>
                            </view>
                            <view class="flex ht-30">
                                <view class="co-9e" style="margin-right: 15px;">门店</view>
                                <view v-if="bcmAfsOrder.storeCode">[{{ bcmAfsOrder.storeCode }}]{{
                                    bcmAfsOrder.storeName
                                    }}</view>
                                <view v-else>{{ bcmAfsOrder.storeName }}</view>
                            </view>
                            <view class="flex ht-30">
                                <view class="co-9e" style="margin-right: 15px;">申请退款金额</view>
                                <view class="co-red bold">{{ formatPrice(bcmAfsOrder.applyRefundAmount) }}</view>
                            </view>
                            <view class="flex" v-if="bcmAfsOrder.afsReason">
                                <view class="co-9e" style="margin-right: 15px;">售后原因</view>
                                <view class="co-red">{{ bcmAfsOrder.afsReason }}</view>
                            </view>
                            <view class="flex" v-if="bcmAfsOrder.afsDesc">
                                <view class="co-9e" style="margin-right: 15px;">售后详情描述</view>
                                <view>{{ bcmAfsOrder.afsDesc }}</view>
                            </view>
                            <view class="flex" v-if="imgList.length" style="align-items:self-start">
                                <view class="co-9e" style="margin-right: 15px;">售后图片</view>
                                <image-list :list="imgList"></image-list>
                            </view>
                        </view>
                    </template>
                </m-card>
                <m-card :title="true" templateTitle="商品信息" :type="true" v-show="true">
                    <template v-slot:content="">
                        <goods-list :goods-list="bcmAfsOrderGoodsList" type="afs"></goods-list>
                        <view style="padding: 0 15rpx 15rpx 0;">
                            <afs-order-state :scope="bcmAfsOrder" :a="bcmAfsOrder"></afs-order-state>
                        </view>
                    </template>
                </m-card>
            </scroll-view>
        </view>
        <view class="bottom" v-if="bcmAfsOrder?.afsOrderStatus">
            <OrderOperateBtn :scope="bcmAfsOrder" @close="close" @fetchData="billQuery"
                v-model:currentItem="bcmAfsOrder" v-model="bcmAfsOrder" v-model:modalType="modalType"
                v-model:showCancelOrderPopup="showCancelOrderPopup" v-model:isOrderCancel="isOrderCancel"
                v-model:title="title" v-model:showAuditSendAfsPopup="showAuditSendAfsPopup" v-model:dealType="dealType"
                v-model:dealList="dealList" v-model:showConfirmApplyOrderPopup="showConfirmApplyOrderPopup"
                v-model:billType="billType" v-model:showDeliveryCancelPopup="showDeliveryCancelPopup"
                :showConfigModal="showConfigModal"/>
        </view>
        <!-- 取消订单、拒单、驳回入库申请弹窗 -->
        <CancelOrderPopup :show="showCancelOrderPopup" @close="close" :scope="bcmAfsOrder" :title="title"
            :modalType="modalType" :dealList="dealList" :orderCancelReasonType="orderCancelReasonType"
            @select="selectItem" @inputchange="inputChange">
            <template v-slot="">
                <view class="bottom-1">
                    <eui-button type="primary" title="确认" style="width: 50%;"
                        @click="orderSureCancel(bcmAfsOrder, modalType, isOrderCancel, dealType, orderCancelReasonType, rejectReason, orderAction)" />
                </view>
            </template>
        </CancelOrderPopup>
        <!-- 退货退款审核弹窗 -->
        <AuditSendAfsPopup :show="showAuditSendAfsPopup" @close="close" :scope="bcmAfsOrder"
            @submit="submitAuditSendAfs" />
        <!-- 售后审核弹窗 -->
        <ConfirmApplyOrderPopup :show="showConfirmApplyOrderPopup" @close="showConfirmApplyOrderPopup = false"
            @orderAction="acceptAfsApplyOrder"
            @updateConfirmApply="showConfirmApplyOrderPopup = false; showAuditSendAfsPopup = true;"
            :scope="bcmAfsOrder">
        </ConfirmApplyOrderPopup>
        <!-- 取消配送弹窗 -->
        <DeliveryCancelPopup :show="showDeliveryCancelPopup" @close="close" :scope="bcmAfsOrder"
            @select="selectDeliveryCancelItem" @inputchange="inputDeliveryChange" :billType="billType">
            <template v-slot="">
                <view class="bottom-1">
                    <eui-button type="primary" title="确认" style="width: 50%;" singleTag="deliveryCancelSure"
                        @click="deliveryCancelSure" />
                </view>
            </template>
        </DeliveryCancelPopup>
    </eui-background>
</template>
<script setup lang="js">
import { mapState, mapMutations } from 'vuex';
import { ref, onUnmounted, onMounted } from 'vue'
import { onLoad, onShow } from "@dcloudio/uni-app";
import service from '../../../common/service';
import { bcmRequest, getBcmUrl } from '../../../hooks/bcmServices';
import { getBcmDictList, getBcmDictName, getBcmDictItem, formatPrice } from '../../../hooks/bcmUseUntils';
import { orderSureCancel } from './utils/cancelOrder.js'
import { handleBLEdevicess } from '../utils/PrintFormatUtil.js'
import OrderOperateBtn from './components/OrderOperateBtn.vue'
import CancelOrderPopup from './components/CancelOrderPopup.vue'
import AuditSendAfsPopup from './components/AuditSendAfsPopup.vue'
import ConfirmApplyOrderPopup from './components/ConfirmApplyOrderPopup.vue'
import DeliveryCancelPopup from './components/DeliveryCancelPopup.vue'
import GoodsList from '../components/GoodsList.vue'
import AfsOrderState from './components/AfsOrderState.vue'
import mCard from '../components/Card.vue'
import ImageList from '../components/ImageList.vue'
import _img_printer from '../../../static/img/bcmIcons/printer.png'
import {storeToRefs} from 'pinia'
import { getPrintData } from '../utils/PrintFormatUtil.js'
import BluetoothPrinter from '@/common/BluetoothPrinter';
import { useMainStore } from "@/store/modules/store";
import { usePrinterStore } from "@/store/printerStore";
import { usePrintTaskStore } from "@/store/usePrintTaskStore";

const bcmUrl = getBcmUrl();
const mainStore = useMainStore();
const printerStore = usePrinterStore();
const { addTask } = usePrintTaskStore();
const { printTimes, bluetoothPrinter } = storeToRefs(printerStore);

const height = ref(0)
const BillId = ref('');
const bcmAfsOrder = ref({})
const bcmAfsOrderGoodsList = ref([])
const imgList = ref([])

const orderCancelReasonType = ref('')
const rejectReason = ref('')
const orderDeliveryCancelReasonType = ref('')
const orderDeliveryCancelReason = ref('')
const modalType = ref('cancel')
const title = ref('取消订单原因')
const dealType = ref('3')
const billType = ref('2')
const dealList = ref([])

const isOrderCancel = ref(false)
const showCancelOrderPopup = ref(false)
const showAuditSendAfsPopup = ref(false)
const showConfirmApplyOrderPopup = ref(false)
const showDeliveryCancelPopup = ref(false)
const isSkip = ref(false)
const isPrinting = ref(false)
const showConfigModal = ref(false)

onMounted(() => {
    uni.getSystemInfo({
        success: function (res) { // res - 各种参数 
            let info = uni.createSelectorQuery().select(".navigation");
            info.boundingClientRect(function (data) { //data - 各种参数
                // height.value = res.windowHeight - data.height-100;
            }).exec()
        }
    });
})

const billQuery = async (id = BillId.value) => {
    bcmAfsOrder.value = {}
    service.enjoyShowLoading('正在加载...');
    const req = {
        BillId: id,
    };
    const result = await bcmRequest(bcmUrl.orderApi, '售后单表', 'EnjoyBillQuery', req);
    service.enjoyHideLoading();
    if (!!result.ds) {
        bcmAfsOrder.value = result.ds;
        if (result.ds1.length > 0) {
            bcmAfsOrderGoodsList.value = result.ds1;
            bcmAfsOrder.value.bcmAfsOrderGoodsList = result.ds1;
        }
        if (result.ds3.length > 0) {
            bcmAfsOrder.value.bcmAfsOrderPayList = result.ds3
        } else {
            bcmAfsOrder.value.bcmAfsOrderPayList = []
        }
        let afsPicJson = JSON.parse(!!result.ds.afsPic && result.ds.afsPic, undefined);
        imgList.value = (afsPicJson == null) ? !!result.ds.afsPic && result.ds.afsPic.split(',') : afsPicJson;
    } else {
        uni.showToast({
            duration: 3500,
            icon: 'none',
            title: '未查询到数据',
            mask: true,
        });
    }
}

onLoad((option) => {
    if (option.c_id) {
        BillId.value = option.c_id;
        billQuery(BillId.value);  
    }
    showConfigModal.value = option.showModal || false;
    uni.$on('REFRESH_AFS_ORDER_DETAIL_DATA', () => {
        billQuery(BillId.value);  // 自定义的刷新页面数据的方法
    });
})

onUnmounted(() => {
    uni.$off('REFRESH_AFS_ORDER_DETAIL_DATA')
})

const selectDeliveryCancelItem = function (item) {
    orderDeliveryCancelReasonType.value = item;
}

const inputDeliveryChange = function (e) {
    orderDeliveryCancelReason.value = e.detail.value;
}

const addPrintTaskFn = function (v, type = 'afs', isAutoPrint = false) {
	addTask({
		id: type == 'order' ? v.orderNo : v.afsOrderNo,
		task: async () => await handleTaskPrint(v, type, isAutoPrint)
	})
}

const handleTaskPrint = function (order, type, isAutoPrint = false) {
	return new Promise((resolve) => {
		let data = getPrintData(order, type, printTimes.value), skip = isAutoPrint ? '0' : (isSkip.value ? '1' : '0');
		BluetoothPrinter.setDevice(bluetoothPrinter.value).checkAndPrint(data).then((res) => {
			if (res.code == '0') {
				if (type == 'afs') {
					ConfirmAfsOrderPrint(order, skip)
				} else {
					ConfirmOrderPrint(order, skip)
				}
			}
			resolve()
		}).catch(res => {
			if (!isAutoPrint) {
				skipFunc(res?.msg);
			}
		})
	})
}

const acceptAfsApplyOrder = async (dealType,v) => {
	orderAction({
		uniqueKey: '售后单表',
		methodName: 'acceptAfsApplyOrder'
	}, bcmAfsOrder.value, {
		dealType,
		afsOrderId: bcmAfsOrder.value?.afsOrderId
	}, '审核通过', true).then((res) => {
		if (dealType == '1' && !['2', '1'].includes(bcmAfsOrder.value?.syncErpBreakageStatus)&&showConfigModal) {
			uni.navigateTo({
				url: `/pages/BcmViews/PickingOrder/breakage?afsOrderId=` + bcmAfsOrder.value?.afsOrderId + '&type=2'
			});
		}
	})
}

const skipFunc = function (contenet = '打印失败，是否跳过打印流程进行后续操作？') {
	uni.showModal({
		title: '提示',
		content: contenet,
		showCancel: true,
		mask: true,
		success: (res) => {
			if (res.confirm) {
				isSkip.value = true;
				isPrinting.value = false;
				// resolve()
                ConfirmAfsOrderPrint(bcmAfsOrder.value, '1')
			} else {
				skipReset()
			}
		}
	})
}

const setPrint = function (v, type = 'afs', isAutoPrint = false) {
	return new Promise((resolve, reject) => {
		if (mainStore.enjoyServiceIp && mainStore.enjoyServiceIp.EnjoyBCM) {
			if (!isAutoPrint) {
				if (!bluetoothPrinter.value?.deviceId) {
					skipFunc("未设置蓝牙打印机，是否跳过打印？")
					return;
				}
				addPrintTaskFn(bcmAfsOrder.value, type, isAutoPrint)
			} else {
				console.log("当前未设置蓝牙打印机");
				// skipFunc("当前未设置蓝牙打印机，是否跳过打印？")
			}
		}
	})
}

onShow(() => {
	uni.setStorageSync('ispreviewImage', false)
})

const skipReset = () => {
	isPrinting.value = false;
	isSkip.value = false;
}

const deliveryCancelSure = () => {
    orderAction({
        uniqueKey: '售后单表',
        methodName: 'CancelDelivery'
    }, bcmAfsOrder.value, {
        afsOrderDeliveryCancelReason: orderDeliveryCancelReasonType.value?.mustInputFlag == '1' ? orderDeliveryCancelReason.value : orderDeliveryCancelReasonType.value?.name,
        afsOrderDeliveryCancelReasonType: orderDeliveryCancelReasonType.value?.code
    }, '退货配送取消成功', true);
}

const ConfirmAfsOrderPrint = (v, skipPrintFlag = '0') => {
	orderAction({
		uniqueKey: '售后单表',
		methodName: 'ConfirmAfsOrderPrint'
	}, v, {
		afsOrderNo: v.afsOrderNo,
		afsOrderId: v.afsOrderId,
		BillId: v.afsOrderId,
		thirdAfsOrderNo: v.thirdAfsOrderNo,
		extras: {
			operateMode: '手动',
			operateTerminal: 'APP',
			skipPrintFlag
		}
	})
}

const ConfirmOrderPrint = (v, skip = undefined) => {
	orderAction({
		uniqueKey: '订单表',
		methodName: 'confirmOrderPrint'
	}, v, {
		operateMode: '手动',
		operateTerminal: 'APP',
		skipPrintFlag: skip ?? (isSkip.value ? '1' : '0')
	})
}


const selectItem = function (item) {
    orderCancelReasonType.value = item.detail.value;
}

const inputChange = function (e) {
    rejectReason.value = e.detail.value;
}

const skipCancel = () => {
    isPrinting.value = false;
    isSkip.value = false
}

const skip = ( ) => {
    isPrinting.value = false;
    isSkip.value = true
}

const confirmPrint = function () {
    if (!isPrinting.value) {
        isPrinting.value = true;
        let item = bcmAfsOrder.value;
        service.enjoyShowLoading("打印中...");
        handleBLEdevicess({
            v: item,
            type: 'afs',
            reset: {
                skip,
                skipCancel
            }
        }).then(() => {
            orderAction({
                uniqueKey: '售后单表',
                methodName: 'ConfirmAfsOrderPrint'
            }, item, {
                afsOrderNo: item.afsOrderNo,
                afsOrderId: item.afsOrderId,
                BillId: item.afsOrderId,
                thirdAfsOrderNo: item.thirdAfsOrderNo,
                extras: {
                    operateMode: '手动',
                    operateTerminal: 'APP',
                    skipPrintFlag: isSkip.value ? '1' : '0'
                }
            })
        }).finally(() => {
            service.enjoyHideLoading();
            skipCancel()
        })
    } else {
        console.log('正在打印中')
    }
}

const close = () => {
    showAuditSendAfsPopup.value = false
    showConfirmApplyOrderPopup.value = false;
    showCancelOrderPopup.value = false;
    modalType.value = '';
    orderCancelReasonType.value = '';
    orderDeliveryCancelReason.value = '';
    orderDeliveryCancelReasonType.value = {};
    showDeliveryCancelPopup.value = false;
    rejectReason.value = '';
    isOrderCancel.value = false;
}

const submitAuditSendAfs = function (data) {
    orderAction({
        uniqueKey: '售后单表',
        methodName: 'acceptAfsApplyOrder'
    }, bcmAfsOrder.value, data, '退货退款上门取件设置成功！', true);
}


const confirmAudit = () => {
    uni.showModal({
        title: '稽核售后单',
        content: '此操作会获取第三方平台最新售后单状态并同步到中台系统，您确定要“稽核售后单”吗？',
        showCancel: true,
        success: (res) => {
            if (res.confirm) {
                orderAction({
                    uniqueKey: '售后单表',
                    methodName: 'syncPlatformAfsOrder'
                }, bcmAfsOrder.value, {
                    afsOrderId: bcmAfsOrder.value?.afsOrderId
                }, '售后单稽核成功');
            } else { }
        }
    });
}

const orderAction = async function ({
    uniqueKey,
    methodName
}, v, params = undefined, text = '', popup = false, fn = undefined) {
    service.enjoyShowLoading('正在加载...');
    let param = {
        chnlCode: v.chnlCode,
        chnlType: v.chnlType,
        orderNo: v.orderNo,
        storeCode: v.storeCode,
        thirdOrderNo: v.thirdOrderNo,
        orderId: v.orderId,
        afsOrderId: v.afsOrderId,
        ...params,
    }
    const response = await bcmRequest(bcmUrl.orderApi, uniqueKey, methodName, param);
    service.enjoyHideLoading();
    if (text) {
        uni.showToast({
            title: text,
            icon: 'none'
        });
    }
    if (popup) {
        close()
    }
    await billQuery();
    if (fn) {
        fn(v)
    }
    if (params) {
        return response
    }
}

</script>
<style lang="scss" scoped>
@import "@/static/font/enjoyicon/iconfont.css";
@import "../common/common.css";

.bottom-1 {
  display: flex;
  justify-content: center;
  flex: 0 0 auto;
  height: 70rpx;
  padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
  background: $uni-bg-color;
}

.navigation {
  flex: 0 0 auto;
  margin-bottom: 5px;
}

.footer {
  flex: 1;
  padding-bottom: 20rpx;
}

.bottom {
  display: flow-root;
  height: 70rpx;
  padding: $uni-spacing-col-sm*2 $uni-spacing-row-sm;
  text-align: center;
  text-align: right;
  background: $uni-bg-color;
  border-bottom-right-radius: $uni-border-radius-lg;
  border-bottom-left-radius: $uni-border-radius-lg;
}

.m-list-top {
  display: grid;
  padding: 8px 0;
  // border-bottom: 1px solid $uni-border-color;
  font-size: 32rpx;

  grid-template-columns: 52% 48%;
}


.popup-content {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0;
  background-color: #fff;

  .popup-title {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    height: 100rpx;
    padding-right: 36rpx;
    padding-left: 30rpx;
    font-size: 33rpx;
    line-height: 100rpx;
    border-bottom: 1px solid #f1f1f1;
  }

  textarea {
    box-sizing: border-box;
    width: 100%;
    height: 80px;
    padding: 5px;
    margin: 5px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
}
</style>